<template>
  <div class="recommend-products">
    <div class="products-grid">
      <div v-for="product in products" :key="product.id" class="product-card" @click="goToProduct(product.id)">
        <div class="product-image">
          <img v-img-fallback :src="product.image" :alt="product.name" />
          <div class="product-badges">
            <span v-if="product.isHot" class="badge hot">热销</span>
            <span v-if="product.isNew" class="badge new">新品</span>
            <span v-if="product.discount" class="badge discount">{{ product.discount }}折</span>
          </div>
          <div class="product-actions">
            <el-button type="primary" size="small" circle @click.stop="addToCart(product)">
              <el-icon>
                <ShoppingCart />
              </el-icon>
            </el-button>
            <el-button type="info" size="small" circle @click.stop="toggleFavorite(product)">
              <el-icon>
                <Star />
              </el-icon>
            </el-button>
          </div>
        </div>

        <div class="product-info">
          <h4 class="product-name">{{ product.name }}</h4>
          <p class="product-desc">{{ product.description }}</p>

          <div class="product-price">
            <span class="current-price">¥{{ product.price }}</span>
            <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
          </div>

          <div class="product-stats">
            <div class="rating">
              <el-rate v-model="product.rating" disabled size="small" show-score text-color="#ff9900" />
            </div>
            <span class="sales">已售{{ product.sales }}件</span>
          </div>
        </div>
      </div>
    </div>

    <div class="load-more">
      <el-button type="primary" size="large" :loading="loading" :disabled="!hasMore" @click="loadMore">
        {{ hasMore ? '查看更多推荐' : '暂无更多推荐' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart, Star } from '@element-plus/icons-vue'
import { useCartStore } from '@/store/modules/cart'
import { useUserStore } from '@/store/modules/user'
import { resolveImage } from '@/utils/request'
import { productApi } from '@/api/product'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()
const loading = ref(false)
const hasMore = ref(true)
const props = defineProps({
  mode: { type: String, default: 'recommended' },
  limit: { type: Number, default: 8 }
})
const limit = ref(props.limit)

// 推荐商品数据（从后端加载）
const products = reactive([])

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/product/${productId}`)
}

// 添加到购物车
const addToCart = async (product) => {
  if (!userStore.isLoggedIn) {
    userStore.redirectPath = `/product/${product.id}`
    userStore.showLoginModal = true
    ElMessage.warning('请先登录后再操作')
    return
  }
  try {
    await cartStore.addToCart({
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    ElMessage.error('添加失败，请重试')
  }
}

// 切换收藏状态
const toggleFavorite = (product) => {
  if (!userStore.isLoggedIn) {
    userStore.redirectPath = `/product/${product.id}`
    userStore.showLoginModal = true
    ElMessage.warning('请先登录后再操作')
    return
  }
  ElMessage.success('已添加到收藏')
}

// 加载更多商品
const loadMore = async () => {
  if (!hasMore.value) {
    ElMessage.info('暂无更多推荐商品')
    return
  }
  loading.value = true
  try {
    limit.value += 8
    await fetchProducts()
    hasMore.value = false
  } catch (error) {
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

const fetchProducts = async () => {
  try {
    const params = { limit: limit.value }
    let res
    if (props.mode === 'hot') {
      res = await productApi.getHotProducts(params)
    } else if (props.mode === 'new') {
      res = await productApi.getNewProducts(params)
    } else {
      res = await productApi.getRecommendedProducts(params)
    }
    const list = Array.isArray(res?.data) ? res.data : (res?.data?.list || [])
    const mapped = list.map(p => ({
      id: p.id,
      name: p.name,
      description: p.description || p.subtitle,
      image: resolveImage(p.image),
      price: p.price,
      originalPrice: p.originalPrice,
      rating: p.rating,
      sales: p.sales,
      isHot: p.isHot,
      isNew: p.isNew,
      discount: p.originalPrice && p.originalPrice > p.price ? (Math.round((p.price / p.originalPrice) * 100) / 10).toFixed(1) : null
    }))
    if (mapped.length > 0) {
      products.splice(0, products.length, ...mapped)
    }
  } catch (e) {
    console.error('加载商品失败:', e)
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.recommend-products {
  width: 100%;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-xxl);
}

.product-card {
  background-color: var(--bg-white);
  border-radius: var(--radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-normal);
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
}

.product-image {
  position: relative;
  width: 100%;
  height: 240px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-normal);
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-badges {
  position: absolute;
  top: var(--spacing-sm);
  left: var(--spacing-sm);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.badge {
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-bold);
  color: var(--text-white);
  line-height: 1;
}

.badge.hot {
  background-color: var(--danger-color);
}

.badge.new {
  background-color: var(--success-color);
}

.badge.discount {
  background-color: var(--warning-color);
}

.product-actions {
  position: absolute;
  top: var(--spacing-sm);
  right: var(--spacing-sm);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  opacity: 0;
  transform: translateX(10px);
  transition: all var(--transition-normal);
}

.product-card:hover .product-actions {
  opacity: 1;
  transform: translateX(0);
}

.product-info {
  padding: var(--spacing-lg);
}

.product-name {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
  line-height: var(--line-height-tight);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-desc {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-md) 0;
  line-height: var(--line-height-normal);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md);
}

.current-price {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--danger-color);
}

.original-price {
  font-size: var(--font-size-base);
  color: var(--text-secondary);
  text-decoration: line-through;
}

.product-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating {
  display: flex;
  align-items: center;
}

.sales {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.load-more {
  text-align: center;
  padding: var(--spacing-xl) 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: var(--spacing-md);
  }
}

@media (max-width: 768px) {
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: var(--spacing-sm);
  }

  .product-image {
    height: 200px;
  }

  .product-info {
    padding: var(--spacing-md);
  }

  .product-name {
    font-size: var(--font-size-base);
  }

  .current-price {
    font-size: var(--font-size-lg);
  }
}

@media (max-width: 480px) {
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .product-image {
    height: 160px;
  }

  .product-info {
    padding: var(--spacing-sm);
  }

  .product-name {
    font-size: var(--font-size-sm);
  }

  .product-desc {
    font-size: var(--font-size-xs);
  }

  .current-price {
    font-size: var(--font-size-base);
  }

  .product-actions {
    display: none;
  }
}
</style>
